import { clearCookie, getCookie, setCookie } from '@/utils/cookie'
import * as TYPES from './types'
import { Module } from 'vuex';
import {RootStateInterface} from './rootStateInterface'
import { userDetail } from '@/http/api'
export interface UserState {
  token: string | null,
  userDetail: any,
}

const user: Module<UserState, RootStateInterface> = {
  // namespaced: true, // 防止模块命名冲突 设置后调用mutations和action需要'模块名/方法' 例如  user/getToken
  getters: {
    getToken: (state) => {
      return state.token = getCookie('token')
    },
    getUserDetail: state => state.userDetail
  },
  mutations: {
    // 登陆成功存储token
    [TYPES.SET_TOKEN](state, token: string) {
      state.token = token;
      setCookie('token',state.token)
    },
    // 退出登录
    [TYPES.OUT_LOGIN]() {
      clearCookie('token')
      window.sessionStorage.removeItem('breadcrumb')
    },
    [TYPES.SET_USERDETAIL](state, data: any) {
      state.userDetail = data
    }
  },
  actions: {
    getUserDetail(state) {
      return new Promise((resole,inject) => {
        userDetail().then(res => {
          state.commit('SET_USERDETAIL', res)
          resole(res)
        }).catch(error => {
          inject(error)
        })
      }) 
    }
  },
}

export default user